<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 搜索添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" stripe="">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <!-- 插槽取到这一行的所有数据，然后.出布尔值，赋值给switch开关按钮 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <!-- 操作按钮 -->
            <!-- 修改 -->

            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 插槽取到这一行数据的id在函数里面传参用于发送查询这天id数据的请求 -->
            <!-- 删除 -->
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <!-- 设置 -->
            <!-- 带提示的按钮 -->
            <el-tooltip
              effect="dark"
              content="设置"
              placement="top-start"
              :enterable="false"
            >
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-setting"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页模块 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="45%"
      @close="addDialogClosed"
    >
      <!-- 主题内容 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">提 交</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息模块 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="45%"
      @close="editDialogClosed"
    >
      <!-- 内容 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    // 验证邮箱规则
    var checkEmail = (rule, value, cb) => {
      // 邮箱正则
      const regEmail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入正确的邮箱!'))
    }
    // 验证手机号规则
    var checkMobile = (rule, value, cb) => {
      // 手机号正则
      const regMobile = /^[1][3,4,5,7,8][0-9]{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入正确的手机号!'))
    }
    return {
      //获取到用户列表的参数对象
      queryInfo: {
        // 查询
        query: '',
        // 这是当前的页数
        pagenum: 1,
        // 每页几条数据
        pagesize: 2,
      },
      userList: [],
      total: 0,
      // 控制添加用户对话框显示与隐藏
      addDialogVisible: false,
      // 添加用户数据
      addForm: {
        username: '',
        password: '',
        email: '',
      },
      // 添加用户表单验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名!', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在3-10个字符!', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码!', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在6-15个字符!', trigger: 'blur' },
        ],
        email: [
          { required: true, message: '请输入正确的邮箱!', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          {
            required: true,
            message: '请输入正确的手机号!',
            trigger: 'blur',
          },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的用户信息对象
      editForm: {},
      // 修改表单的验证规则对象
      editFormRules: {
        email: [
          { required: true, message: '请输入正确的邮箱!', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          {
            required: true,
            message: '请输入正确的手机号!',
            trigger: 'blur',
          },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户列表数据的请求
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo,
      })
      if (res.meta.status == !200)
        return this.$message.error('获取用户数据失败！')
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听pagesiae（每页显示条数）改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      // 重新获取数据
      this.getUserList()
      console.log(newSize)
    },
    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      // 重新获取数据
      this.getUserList()
      console.log(newPage)
    },
    // 监听switch开关状态的改变
    async userStateChanged(userInfo) {
      // put请求存储信息的users/:uId/state/:type带冒号是需要动态切换想存储的信息
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新用户状态失败！')
        // 存储失败需要取反
      }
      this.$message.success('更新用户状态成功！')
    },
    // 监听添加用户对话框的关闭事件,关闭清空表单
    addDialogClosed() {
      // this.addForm={}此方法无法关闭表单验证规则
      this.$refs.addFormRef.resetFields()
    },
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        //如果校验不成功就return
        if (!valid) return
        //可以发送提交的网络请求
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败!')
        }
        this.$message.success('添加用户成功!')
        // 同时把对话框隐藏并且重新刷新用户列表
        this.addDialogVisible = false
        // 刷新用户列表
        this.getUserList()
      })
    },
    // 展示修改用户对话框的关闭事件
    async showEditDialog(id) {
      // console.log(id)
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('查询用户失败!')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 监听修改用户信息对话框的关闭事件,重置验证状态
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户信息提交函数
    editUserInfo() {
      // 预验证
      this.$refs.editFormRef.validate(async (valid) => {
        // 如果值为false就不通过return
        if (!valid) return
        // 发起修改用户信息请求
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          }
        )
        if (res.meta.status !== 200)
          return this.message.error('修改用户信息失败！')
        // 关闭对话框
        this.editDialogVisible = false
        // 刷新数据列表
        this.getUserList()
        // 提示修改成功
        this.$message.success('用户信息更新成功！')
      })
    },
    // 根据id删除用户信息并提交
    async removeUserById(id) {
      // console.log(id)
      // 弹框确认是否删除
      // 使用$confirm 需要全局挂载后使用
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // 点取消会触发$confirm里面的报错使用.catch捕获报错并且return出去
      // .catch((err) => {
      //   return err
      // })  的简写

      // 如果用户确认删除则返回值为字符串confirm
      // 如果取消则返回字符串cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除！')
      }
      // console,log('确认了删除！')
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败！')
      }
      this.getUserList()
      this.$message.success('删除成功！')
    },
  },
}
</script>
<style lang="less" scoped>
.el-pagination {
  text-align: center;
}
</style>